package com.asiainfo.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.asiainfo.bean.MealBean;
import com.asiainfo.bean.UserSessionBean;
import com.asiainfo.dao.BaseDao;
import com.asiainfo.util.DBSequence;
import com.asiainfo.util.SessionInfoUtil;

@Controller
@RequestMapping("/mealController")
public class MealController extends ModelAndView{

	private Logger logger = LogManager.getLogger(this.getClass());
	
	/**
	 * 数据操作封装DAO
	 */
	@Autowired
	private BaseDao dao;
	
	/**
	 * 方法描述：跳转到套餐列表页面
	 * 
	 * return 套餐列表页面页面Model
	 */
	@RequestMapping("/mealListView.do")
	public ModelAndView mealList() {
		this.setViewName("business/mealList");
		return this;	
	}
	
	
	/**
	 * 我的所有可选套餐
	 * @param mealBean 我所属运营商的id（1是移动，2是联通）
	 * @param request 返回当前号码所属运营商下所有套餐
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/myAllOkMeal.do")
	public @ResponseBody
	JSONObject myAllOKMeal(@RequestBody MealBean mealBean, 
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		JSONObject retMsg = new JSONObject();
		
		UserSessionBean userSessionBean = SessionInfoUtil.getUserSessBean(request.getSession());
		List<MealBean> mealBeanList= new ArrayList<MealBean>();
		//session 为空时需求重新登录。
		if(null == userSessionBean)
		{
			logger.error("session 为空时需求重新登录。");
			retMsg.put("flag", false);
		}else
		{
			String operatorId =  userSessionBean.getOperatorId();
			//获得所有可选套餐
			mealBeanList = dao.getDAO().selectList(
						"MealController.queryMealList", operatorId);
			retMsg.put("flag", true);
		}
		this.addObject(mealBeanList);
		return retMsg;
	}
	
	/**
	 * 我的所有订购套餐
	 * @param mealBean 我号码phone,套餐序列号serial_number（1是移动，2是联通）
	 * @param request 返回当前号码所属运营商下所有套餐
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/orderMeal")
	public @ResponseBody
	JSONObject addMyMeal(@RequestBody MealBean mealBean, 
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		JSONObject retMsg = new JSONObject();
		UserSessionBean userSessionBean = SessionInfoUtil.getUserSessBean(request.getSession());
		if(null == userSessionBean)
		{
			logger.error("session 为空时需求重新登录。");
			retMsg.put("flag", false);
		}else
		{
			if(null!=mealBean)
			{
				String serialNumber =  mealBean.getSerial_number();
				if(!serialNumber.isEmpty()&&!"null".equals(serialNumber)&&!"".equals(serialNumber))
				{
					SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");//设置日期格式
					mealBean.setManagement_date(df.format(new Date()));
					mealBean.setMenu_id(DBSequence.getInstance().getSequence());
					mealBean.setPhone(userSessionBean.getPhone());
					mealBean.setExpiry_date(getDate(df));
					
					List<MealBean> mealList = new ArrayList<MealBean>();
					mealList = dao.getDAO().selectList("MealController.queryMyMealList", mealBean);
					if(0<mealList.size())
					{
						logger.error("当前套餐已订购，不可再订购。");
						retMsg.put("have", true);
					}else
					{
						dao.getDAO().insert("MealController.insertMyMeal", mealBean);
						retMsg.put("flag", true);
					}
				}else
				{
					logger.error("订购套餐ID不合法，serialNumber: "+mealBean.getSerial_number());
					retMsg.put("flag", false);
				}
			}else
			{
				logger.error("订购事件 没有取到套餐ID 。");
				retMsg.put("flag", false);
			}
		}
		return retMsg;
	}
	/**
	 * 当前日期加一年
	 * @param df
	 * @return
	 */
	public static String getDate(SimpleDateFormat df){
		Calendar cale = Calendar.getInstance();  
		cale.set(Calendar.YEAR,cale.get(Calendar.YEAR)+1);
        Date date=cale.getTime();
		return df.format(date);
	}
}